<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>万东影院 | 注册</title>
  <link th:href="@{/images/logo.svg}" rel="icon" type="image/svg+xml">
  <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
  <link th:href="@{/css/bootstrap-icons.min.css}" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
  <div class="d-flex justify-content-center align-items-center vh-100">
    <div class="border rounded-3 p-3 w-25">
      <div class="mt-2 mb-3 mx-3">
        <img th:src="@{/images/logo.svg}" alt="logo" style="width: 100px">
        <span class="h4 ms-4 text-center">注册新账户</span>
      </div>
      <form class="d-flex flex-column gap-3" id="form">
        <div class="form-floating">
          <input id="usernameInput" class="form-control"
                 name="username" placeholder="输入用户名">
          <label for="usernameInput">用户名</label>
        </div>
        <div class="form-floating">
          <input id="passwordInput" class="form-control" type="password"
                 name="password" placeholder="输入密码">
          <label for="passwordInput">密码</label>
        </div>
        <div class="form-floating">
          <input id="phoneNumberInput" class="form-control"
                 name="phoneNumber" placeholder="输入手机号">
          <label for="phoneNumberInput">手机号</label>
        </div>
        <div class="d-flex">
          <a class="btn btn-link" th:href="@{/login}">已有账号？选择登录</a>
        </div>
        <button class="btn btn-primary"
                type="submit" id="submitButton">注册</button>
      </form>
    </div>
  </div>
</div>
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
<script>
const form = document.getElementById("form");
const submitButton = document.getElementById("submitButton");

async function submitForm() {
  const formData = new FormData(form);

  const data = {};
  formData.forEach((value, key) => {
    data[key] = value;
  });

  try {
    const response = await axios.post('/auth/register', data, {
      headers: {'Content-Type': 'application/json'}
    });

    if (response.status === 200) {
      alert("注册用户成功");
      location.href = '/login';
    }
  } catch (error) {
    if (!error.response) {
      console.log(error);
    }
    else if (error.response.status === 400) {
      alert(error.response.data);
    }
  }
}

submitButton.addEventListener("click", event => {
  event.preventDefault();
  submitForm();
});
</script>
</body>
</html>